package com.smalls.redshoes.util;

import android.text.TextUtils;

import com.smalls.newvideotwo.NewDTVApp;
import com.smalls.newvideotwo.util.LogUtil;
import com.smalls.newvideotwo.utils.Constant;
import com.uking.helper.VKNetBossUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;

public class CacheUtils {
    public static final String CATEGORY_CACHE_FILE_NAME = "category";
    public static String DIRECTORY_DOCUMENTS = "Documents";
    public static String DIRECTORY_FILES = "";
    public static String DIRECTORY_PICTURES = "Pictures";
    private static String TAG = com.smalls.newvideotwo.utils.Constant.baddcoolio2tag? com.smalls.newvideotwo.utils.Constant.TAGPREFIXSTR + "CacheUtils":"CacheUtils";

    public static String getCachePath(String type) {
        LogUtil.d(TAG, "getCachePath");
        String path = NewDTVApp.getApp().getExternalFilesDir(type).getPath() + "/";
        LogUtil.d(TAG, "path=" + path);
        return path;
    }

    public static void writeDocumentFile(String fileName, String fileContent) {
        LogUtil.d(TAG, "writeDocumentFile");
        String encryptString = VKNetBossUtils.encrypt(fileContent, Constant.KEY);
        String path = getCachePath(DIRECTORY_DOCUMENTS);
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        try {
            FileOutputStream out = new FileOutputStream(path + fileName);
            out.write(encryptString.getBytes());
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String readDocumentFile(String fileName) {
        LogUtil.d(TAG, "readDocumentFile=" + fileName);
        StringBuffer sb = new StringBuffer();
        try {
            String filePath = getCachePath(DIRECTORY_DOCUMENTS) + fileName;
            LogUtil.d(TAG, "readDocumentFile filePath=" + filePath);
            String encoding = "utf-8";
            File file = new File(filePath);
            if (file.isFile() && file.exists()) {
                InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);
                BufferedReader bufferedReader = new BufferedReader(read);
                while (true) {
                    String lineTxt = bufferedReader.readLine();
                    if (lineTxt == null) {
                        break;
                    }
                    sb.append(lineTxt);
                }
                read.close();
            }
        } catch (Exception e) {
            LogUtil.d(TAG, "readDocumentFile=" + e.toString());
            e.printStackTrace();
        }
        if (TextUtils.isEmpty(sb.toString())) {
            return null;
        }
        return VKNetBossUtils.decrypt(sb.toString(), Constant.KEY);
    }
}
